package com.nettyRpc.consumer;


import com.nettyRpc.api.DubboResult;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 存储
 */

public class DubboFuture {



    private static final Map<Long, DubboFuture> FUTURES = new ConcurrentHashMap<>();

    private long id;

    private static DubboResult response;

    public DubboFuture() {

    }

    public DubboFuture(long id) {
        this.id = id;
        FUTURES.put(id, this);
    }

    public DubboResult get() {
        synchronized (this) {
            while (isDone()) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return response;
    }

    private void doReceived(DubboResult result) {
        synchronized (this) {
            response = result;
            notifyAll();
        }
    }

    public static void received(DubboResult result) {
        DubboFuture future = FUTURES.remove(result.getId());
        if (future != null) {
            future.doReceived(result);
        } else {
            System.out.println("The timeout response finally returned at "
                    + (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date())));
        }
    }

    public boolean isDone() {
        return response == null;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

}
